<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建日期" prop="createdAt">
        <el-date-picker clearable
          v-model="queryParams.createdAt"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择创建日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['users:users:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['users:users:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['users:users:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="usersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" />
      <el-table-column label="序号" align="center" type="index" width="80"/>
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="1-学生 2-家长" align="center" >
          <template #default="scope">
            <el-text v-if="scope.row.userType === 1">学生</el-text>
              <el-text v-if="scope.row.userType === 2">家长</el-text>
          </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="邮箱" align="center" prop="email" width="250"/>
      <el-table-column label="0-禁用 1-正常" align="center" prop="status">
          <template #default="scope">
              <el-text v-if="scope.row.status === 0">禁用</el-text>
              <el-text v-if="scope.row.status === 1">正常</el-text>
          </template>
      </el-table-column>
      <el-table-column label="违规次数" align="center" prop="violationCount" />
      <el-table-column label="最后警告时间" align="center" prop="lastWarningTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastWarningTime, '{y}-{m}-{d}-{h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}-{h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
        <el-table-column label="修改时间" align="center" prop="updatedAt" width="180">
            <template #default="scope">
                <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}-{h}:{i}:{s}') }}</span>
            </template>
        </el-table-column>
      <el-table-column label="操作" align="center" >
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['users:users:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['users:users:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户基础对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="usersRef" :model="form" :rules="rules" label-width="80px">
          用户名：<el-input v-model="form.username" style="width: 240px" disabled/><br>
          状态：
          <el-radio-group v-model="form.status">
              <el-radio :value="0">禁用</el-radio>
              <el-radio :value="1">启用</el-radio>
          </el-radio-group><br>
          违规次数：<el-input-number v-model="form.violationCount" :min="0" :max="3" @change="handleChange(form.violationCount)" /><br/>
          最近警告时间：<el-input v-model="form.lastWarningTime" style="width: 240px" disabled/>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Users">
import { listUsers, getUsers, delUsers, addUsers, updateUsers } from "@/api/users/users"

const { proxy } = getCurrentInstance()

const usersList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    username: null,
    password: null,
    userType: null,
    createdAt: null,
    updatedAt: null
  },
  rules: {
    username: [
      { required: true, message: "用户名不能为空", trigger: "blur" }
    ],
    password: [
      { required: true, message: "加密密码不能为空", trigger: "blur" }
    ],
    userType: [
      { required: true, message: "1-学生 2-家长不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询用户基础列表 */
function getList() {
  loading.value = true
  listUsers(queryParams.value).then(response => {
    usersList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    username: null,
    password: null,
    userType: null,
    phone: null,
    email: null,
    status: null,
    violationCount: null,
    lastWarningTime: null,
    createdAt: null,
    updatedAt: null
  }
  proxy.resetForm("usersRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加用户基础"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getUsers(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改用户基础"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["usersRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateUsers(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addUsers(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除用户基础编号为"' + _ids + '"的数据项？').then(function() {
    return delUsers(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('users/users/export', {
    ...queryParams.value
  }, `users_${new Date().getTime()}.xlsx`)
}
getList()

function handleChange(value) {
//如果违规次数等于三则自动禁用用户 恢复到小于三的时候就会恢复用户状态
    if (value === 3) {
        form.value.status = 0
    }
    if (value < 3) {
        form.value.status = 1
    }
    if (value === 0){
        // 恢复状态并清除警告时间
        form.value.lastWarningTime =  null
    }
    //如果违规次数加一次就会设置最近警告时间
    if (value > 0) {
        form.value.lastWarningTime = new Date().toLocaleString()
    }
}
</script>
